package com.quanshu.exchange.support.config;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;

import com.quanshu.exchange.support.utils.LogUtil;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public abstract class PermissionObserver implements Observer<Boolean> {

    public static final int REQUEST_SETTING = 200;//前往设置界面的requestCode

    private Activity activity;

    public PermissionObserver(Activity activity) {
        this.activity = activity;
    }

    @Override
    public void onError(Throwable e) {
        LogUtil.printException(e);
    }

    @Override
    public void onComplete() {

    }

    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(Boolean granted) {
        LogUtil.print("granted=" + granted);
        // 在android 6.0之前会默认返回true
        if (granted) {
            // 已经获取权限
            onSuccess();
        } else {
            // 未获取权限
            onFailure();
        }
    }

    public abstract void onSuccess();

    public void onFailure() {
        showSettingDialog();
    }

    private void showSettingDialog() {
        LogUtil.printStack();
        new AlertDialog.Builder(activity)
                .setMessage("您没有授权该权限，请在设置中打开授权")
                .setPositiveButton("确定", (arg0, arg1) -> {
                    arg0.dismiss();
                    gotoSetting();
                })
                .setNegativeButton("取消", (arg0, arg1) -> arg0.dismiss()).show();
    }

    private void gotoSetting() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
        intent.setData(uri);
        activity.startActivityForResult(intent, REQUEST_SETTING);
    }
}